package com.wang.mall.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.enums.ApiErrorCode;
import com.baomidou.mybatisplus.extension.exceptions.ApiException;

import com.wang.mall.service.SysLoginService;
import com.wang.mall.service.SysMenuService;
import com.wang.mall.bean.SysMenu;
import com.wang.mall.feign.JwtToken;
import com.wang.mall.feign.OauthServerFeign;
import com.wang.mall.model.LoginResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class SysLoginServiceImpl implements SysLoginService {


    @Autowired
    private OauthServerFeign oauthServerFeign;

    @Autowired
    private SysMenuService sysMenuService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Value("${basic.token:Basic bWFsbC1hcGk6bWFsbC1zZWNyZXQ=}")
    private String basicToken;

    @Override
    public LoginResult login(String username, String password) {
        LoginResult loginResult = new LoginResult();

        ResponseEntity<JwtToken> responseEntity = null;
        try {
            responseEntity = oauthServerFeign.oauth("password", username, password, "admin_type", basicToken);
        } catch (Exception e) {
            throw new UsernameNotFoundException("用户名或者密码错误");
        }

        // 判断是否登陆成功
        if (responseEntity.getStatusCode() != HttpStatus.OK) {
            throw new ApiException(ApiErrorCode.FAILED);
        }

        JwtToken jwtToken = responseEntity.getBody();

        // 设置token
        String accessToken = jwtToken.getAccessToken();
        loginResult.setToken(accessToken);


        Jwt jwt = JwtHelper.decode(accessToken);
        String jwtClaims = jwt.getClaims();
        JSONObject jsonObject = JSON.parseObject(jwtClaims);
        Long userId = Long.valueOf(jsonObject.getString("user_name"));
        // 查询菜单信息, 权限数据
        List<SysMenu> sysMenuList = sysMenuService.getMenusByUserId(userId);
        loginResult.setMenus(sysMenuList);


        // 给redis保存一份数据
        // 过期时间
        redisTemplate.opsForValue().set(accessToken, jsonObject.getString("user_name"), 7 * 24 * 3600, TimeUnit.SECONDS);

        // 查询权限数据
        JSONArray authoritiesJson = jsonObject.getJSONArray("authorities");
        List<SimpleGrantedAuthority> authorityList = authoritiesJson.stream().map(a -> new SimpleGrantedAuthority(a.toString())).collect(Collectors.toList());
        loginResult.setAuthorities(authorityList);


        return loginResult;
    }
}
